package com.dididoctor.patient.Activity.Message.SystemMessage;

import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.WindowManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Activity.Service.ServiceDetail.ServiceDetailActivity;
import com.dididoctor.patient.Activity.Usercentre.Consume.UserConsumeActivity;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetail.CasesDetailActivity;
import com.dididoctor.patient.Activity.Usercentre.Record.Cases.CasesDetailUp.CasesDetailUpActivity;
import com.dididoctor.patient.Activity.Usercentre.Setting.UserSettingActivity;
import com.dididoctor.patient.Activity.Welcome.WelcomeDialog;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.Http.MyHttpResponseHandler;
import com.dididoctor.patient.MV.BasePresenter;
import com.dididoctor.patient.MV.BusinessClient;
import com.dididoctor.patient.MV.Response;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.Utils.Util;
import com.dididoctor.patient.WYY.CustomAttachmentType;
import com.dididoctor.patient.WYY.Timely.TimelyAttachment;
import com.loopj.android.http.RequestParams;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import org.apache.http.Header;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @version 2.0
 * @类描述：
 * @项目名称：ddgh
 * @类名称： SystemMessagePresenter
 * @包名称： com.dididoctor.patient.Activity.Message.SystemMessage
 * @创建人： zhanjunjie
 * @创建时间：2016/4/14 17:00
 * @修改人：
 * @修改时间：2016/4/14 17:00
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class SystemMessagePresenter extends BasePresenter {

    private SystemMessageView view;

    public SystemMessagePresenter(Context context, SystemMessageView view) {
        super(context, view);
        this.view = view;
    }

    void getmessageInfo(int pageIndex) {
        RequestParams params = new RequestParams();
        params.put("pageIndex", pageIndex);
        params.put("userId", Token.getId());
        params.put("token", Token.getToken());
        params.put("pageSize", "10");
        BusinessClient.post(ConstantValue.message, params, new MyHttpResponseHandler() {

            private List<SystemMessage> messages = new ArrayList<SystemMessage>();
            private List<Map<String, String>> maps = new ArrayList<Map<String, String>>();

            @Override
            public void onMyResponse(Response response) {
                if (response.isSucceed()) {
                    maps = response.getListData("messageList");
                    for (Map<String, String> map : maps) {
                        SystemMessage message = new SystemMessage();
                        String contents = Util.toString(map.get("contents"));
                        if (contents.indexOf("type") !=-1){
                            JSONObject object = JSON.parseObject(contents);
                            String  type = object.getString("type");
                            message.setType(type);
                            if ("1".equals(type)) {
//                                    内容:活动内容(如:迎五一，一毛钱签约医生活动开始了，赶快去签约吧)
//                                    点击:活动详情界面

                                String webUrl = object.getString("webUrl");
                                message.setWebUrl(webUrl);
                                String picUrl = object.getString("picUrl");
                            }else  if ("2".equals(type)){
//                                    内容:您于4月21日 18:24分咨询的问题，医生已经为您下达诊疗建议，可以到个人中心我的病历中查看
//                                    点击:病历详情页
                                String recType =object.getString("recType");
                                String recId = object.getString("recId");
                                message.setRecType(recType);
                                message.setRecId(recId);
                            } else  if ("4".equals(type)){
//                                  内容:您于4月21日 18:24分预约电话服务已经结束，医生已经对您下达诊疗建议，快去看看吧
//                                    点击:跳转病历详情页面
                                String recType =object.getString("recType");
                                String recId = object.getString("recId");
                                message.setRecType(recType);
                                message.setRecId(recId);
                            }else if ("9".equals(type)){
                                //为了统一内容本地将title和contents做了互换
                                String des = object.getString("content").toString();
                                message.setTitle(des);
                            }
                            String des = object.getString("msg");
                            message.setContents(des);
                            message.setStartTime(Util.toString(map.get("startTime")));
                        }else{
                            message.setMessageId(Util.toString(map.get("messageId")));
                            message.setTitle(Util.toString(map.get("title")));
                            message.setContents(Util.toString(map.get("contents")));
                            message.setWebUrl(Util.toString(map.get("webUrl")));
                            message.setProdId(Util.toString(map.get("prodId")));
                            message.setStartTime(Util.toString(map.get("startTime")));
                        }

                        messages.add(message);
                    }
                    view.getmessage(messages);
                } else {
                    view.getmessage(messages);
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                view.getmessagefail();
            }
        });
    }

    void getfindDoctorByIds(String ids, final List<YXBean> ls, final List<TimeBean> time) {
        final RequestParams params = new RequestParams();
//        userId	String	是	用户
//        token	String	是	唯一标示
//        ids	String		id(云信ID)组成的字符串（"1,2,3,4"）
        params.put("userId", Token.getId());
        params.put("token", Token.getToken());
        params.put("ids", ids);
        //                "doctorId": 1,
//                        "sessionId": 23,
//                        "name": "张四",
//                        "hospitalId": 1,
//                        "headPic": "upload/clientHeadPic/2/14600227972181433929700635.jpg",
//                        "hospital": "北京医院"
        BusinessClient.post(ConstantValue.findDoctorByIdsUrl, params, new MyHttpResponseHandler() {

            private List<PersonalBean> messages = new ArrayList<PersonalBean>();

            @Override
            public void onMyResponse(Response response) {

//                private String messageAttachType;
//                private String patientName;
//                private String age;
//                private String illName;
//                private String patientHeadPic;
//                private String recId;
//                private String suggestion;//诊疗建议
//                private String suggestionResult;//诊疗结果
//                private String disId;
                if (response.isSucceed()) {
                    List<Map<String, String>> doctorList = response.getListData("doctorList");
                    for (int x = 0; x < doctorList.size(); x++) {
                        PersonalBean message = new PersonalBean();
                        message.setDoctorId(Util.toString(doctorList.get(x).get("doctorId")));
                        message.setSessionId(Util.toString(doctorList.get(x).get("sessionId")));
                        message.setName(Util.toString(doctorList.get(x).get("name")));
                        message.setHospitalId(Util.toString(doctorList.get(x).get("hospitalId")));
                        message.setHeadPic(Util.toString(doctorList.get(x).get("headPic")));
                        message.setHospital(Util.toString(doctorList.get(x).get("hospital")));
                        message.setIsSign(Util.toString(doctorList.get(x).get("isSign")));

                        for (int y = 0; y < ls.size(); y++) {
                            if (Util.toString(doctorList.get(x).get("sessionId")).equals(ls.get(y).getAddId())) {
                                if (ls.get(y).getData() != null) {
                                    if (ls.get(y).getMsgType() == MsgTypeEnum.custom) {
                                        com.alibaba.fastjson.JSONObject object = JSON.parseObject(ls.get(y).getData());
                                        String patientName = "";
                                        String age = "";
                                        String illName = "";
                                        String patientHeadPic = "";
                                        String recId = "";
                                        String suggestion = "";
                                        String suggestionResult = "";
                                        String disId = "";
                                        String patientPhone = "";
                                        if (Integer.parseInt(object.get("messageAttachType").toString()) == CustomAttachmentType.APPOINTMENTPHONE) {
                                            patientName = object.get("patientName").toString();
                                            age = object.get("age").toString();
                                            illName = object.get("illName").toString();
                                            patientHeadPic = object.get("patientHeadPic").toString();
                                            recId = object.get("recId").toString();
                                            suggestion = "一条电话预约消息";
                                            suggestionResult = object.get("suggestionResult").toString();
                                            disId = object.get("disId").toString();
                                            patientPhone = object.get("patientPhone").toString();
                                        } else if (Integer.parseInt(object.get("messageAttachType").toString()) == CustomAttachmentType.RTS) {
                                            patientName = object.get("patientName").toString();
                                            age = object.get("age").toString();
                                            illName = object.get("illName").toString();
                                            patientHeadPic = object.get("patientHeadPic").toString();
                                            recId = object.get("recId").toString();
                                            suggestion = "一条问诊表消息";
                                            suggestionResult = object.get("suggestionResult").toString();
                                            disId = object.get("disId").toString();
                                        } else if (Integer.parseInt(object.get("messageAttachType").toString()) == CustomAttachmentType.MEDICCALADVICE) {
                                            patientName = object.get("patientName").toString();
                                            age = object.get("age").toString();
                                            illName = object.get("illName").toString();
                                            patientHeadPic = object.get("patientHeadPic").toString();
                                            recId = object.get("recId").toString();
                                            suggestion = object.get("suggestion").toString();
                                            suggestionResult = object.get("suggestionResult").toString();
                                            disId = object.get("disId").toString();
                                        } else if (Integer.parseInt(object.get("messageAttachType").toString()) == CustomAttachmentType.TIMELYPHONE) {
                                            patientName = object.get("patientName").toString();
                                            age = object.get("age").toString();
                                            illName = object.get("illName").toString();
                                            patientHeadPic = object.get("patientHeadPic").toString();
                                            recId = object.get("recId").toString();
                                            suggestion = "一条即时电话消息";
                                            suggestionResult = object.get("suggestionResult").toString();
                                            disId = object.get("disId").toString();
                                        }

                                        message.setPatientName(patientName);
                                        message.setAge(age);
                                        message.setIllName(illName);
                                        message.setPatientHeadPic(patientHeadPic);
                                        message.setRecId(recId);
                                        message.setSuggestion(suggestion);
                                        message.setStatus(ls.get(y).getStatus());

                                        message.setSuggestionResult(suggestionResult);
                                        message.setDisId(disId);
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String sd = sdf.format(new Date(Long.parseLong(time.get(y).getTime())));
                                        message.setTime(sd);
                                    } else if (ls.get(y).getMsgType() == MsgTypeEnum.tip) {
                                        message.setSuggestion(ls.get(y).getData());
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String sd = sdf.format(new Date(Long.parseLong(time.get(y).getTime())));
                                        message.setTime(sd);
                                        message.setStatus(ls.get(y).getStatus());
                                    } else if (ls.get(y).getMsgType() == MsgTypeEnum.text) {
                                        message.setSuggestion(ls.get(y).getData());
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String sd = sdf.format(new Date(Long.parseLong(time.get(y).getTime())));
                                        message.setTime(sd);
                                        message.setStatus(ls.get(y).getStatus());
                                    } else if (ls.get(y).getMsgType() == MsgTypeEnum.image) {
                                        message.setSuggestion("一张" + ls.get(y).getData() + "消息");
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String sd = sdf.format(new Date(Long.parseLong(time.get(y).getTime())));
                                        message.setTime(sd);
                                        message.setStatus(ls.get(y).getStatus());
                                    } else if (ls.get(y).getMsgType() == MsgTypeEnum.audio) {
                                        message.setSuggestion("一条" + ls.get(y).getData() + "消息");
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String sd = sdf.format(new Date(Long.parseLong(time.get(y).getTime())));
                                        message.setTime(sd);
                                        message.setStatus(ls.get(y).getStatus());
                                    }
                                    messages.add(message);
                                }
                            }
                        }
                    }
                    view.getPersonalmessage(messages);
                } else {
                    view.showToastMessage(response.getMsg());
                    view.getmessagefail();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                view.getmessagefail();
            }
        });
    }

    public void getgoAndFrom(final String hosId, final String doctorID, final String addId, final String isSign, final String name) {
//        hosId	String	是	医生所属医院id
        RequestParams params = new RequestParams();
        params.put("userId", Token.getId());
        params.put("token", Token.getToken());
        params.put("hosId", hosId);
        BusinessClient.post(ConstantValue.medicalchatUrl, params, new MyHttpResponseHandler() {
            private String hasDoctor = "";//是否有签约医生1有0没有

            @Override
            public void onMyResponse(Response response) {
                if ("1".equals(response.getStatus())) {
                    String isCmp = response.getString("isCmp");
                    String recId = response.getString("recId");
//                    view.IntentInquiryActivity(isCmp, hosId, doctorID, addId);
                    view.IntentP2PActivity(recId, "4", hosId, doctorID, addId, isSign,name);
                } else if ("2".equals(response.getStatus())) {
                    String recId = response.getString("recId");
                    view.IntentP2PActivity(recId, "2", hosId, doctorID, addId, isSign,name);
                } else if ("3".equals(response.getStatus())) {
                    String recId = response.getString("recId");
                    view.IntentP2PActivity(recId, "3", hosId, doctorID, addId, isSign,name);
                } else if ("4".equals(response.getStatus())) {
                    String recId = response.getString("recId");
                    view.IntentP2PActivity(recId, "4", hosId, doctorID, addId, isSign,name);
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                super.onFailure(i, headers, bytes, throwable);
                view.getdoctorfail();
            }
        });
    }

}
